﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Rappelz.GameServer;
using Rappelz.GameServer.Scripting;

namespace GameServer
{
    public partial class formGameServer : Form
    {
        public delegate void SafeUpdateServer(int idx, string name, string status, int users);
        public delegate void SafeUpdateStatus(string status);

        public static formGameServer Instance;

        private int logEventRecursiveDoEventCount = 0;

        public formGameServer()
        {
            InitializeComponent();
            Instance = this;
            RappelzServer.CreateInstance();
        }

        public void addLogLine(string text)
        {
            if (tbLogBox.IsDisposed || cbActivateLog.CheckState != CheckState.Checked)
                return;

            if (tbLogBox.InvokeRequired)
            {

                //we are not, so an invoke is required.
                Delegate d = new SafeUpdateStatus(addLogLine);
                tbLogBox.BeginInvoke(d, text);
            }
            else
            {
                if (logEventRecursiveDoEventCount > 50)
                {
                    tbLogBox.AppendText("Too many log request at the same time, desactivating logging on gui (view the log file for full log)." + Environment.NewLine);
                    cbActivateLog.CheckState = CheckState.Unchecked;
                    logEventRecursiveDoEventCount = 0;
                    return;
                }

                if(cbActivateLog.CheckState == CheckState.Checked)
                    tbLogBox.AppendText(text);

                //In case something send a massive amount of log text, the gui become unresponsive, this instruction makes the gui respond to user request (like untick the "Show Log messages" checkbox)
                //logEventRecursiveDoEventCount prevent too many recursive call to DoEvent
                logEventRecursiveDoEventCount++;
                Application.DoEvents();
                logEventRecursiveDoEventCount--;
            }
        }

        private void formGameServer_FormClosing(object sender, FormClosingEventArgs e)
        {
            RappelzServer.Instance.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            LuaVM.ResetLua();
            LuaVM.Init();
        }

        private void bnReloadQuests_Click(object sender, EventArgs e)
        {
            GameContent.ReloadQuests();
        }

        private void btClearLog_Click(object sender, EventArgs e)
        {
            tbLogBox.Clear();
        }

        private void formGameServer_Load(object sender, EventArgs e)
        {

        }
    }
}
